<?php
require("config.php");
require("db_mysql.inc");
require("functions.php");
$db = new ps_DB;

$isNewEntry = $_POST['isNewEntry'];
$rating = $_POST['safetyRating'];
$comment = $_POST['safetyComment'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];

if($isNewEntry == "true" )
	createMarker($lat, $lng, $comment, $rating, $db);

?>


<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		html { height: 100% }
		body { height: 100%; margin: 0px; padding: 0px }
		#map_canvas { height: 100% }
	 </style>
	<script type="text/javascript"  src="http://maps.google.com/maps/api/js?sensor=true"></script>
	<script type="text/javascript">

	/*
	 *	Set initial parameters and initialize map.
	 *	Set initial location to user's current location if available, else use a default value.
	 */
	function initialize()
	{
		//	Set default position to Melbourne
		var initialLocation = new google.maps.LatLng(-37.80246476053294, 144.96681494140626);

		var myOptions = {
			zoom: 10,
			center: initialLocation,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

		//	If geolocation is available and gets current position, use it.
		if(navigator.geolocation) 
		{
			navigator.geolocation.getCurrentPosition(function(position) 
				{
						initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
						map.setCenter(initialLocation);
						initializeMap(map, initialLocation);
				}, function() {
						initializeMap(map, initialLocation);
				}
			);
		}
		else
			initializeMap(map, initialLocation);
 	}
 	
	/*
	 *	Put all the markers on the map and add listeners for them.
	 *	Also show startup window.
	 */
 	function initializeMap(map, location)
 	{
		//	Put in all the markers for the places that have been marked so far
		populateMarkers(map);

		//	Add listener for when user wants to mark a position as unsafe
		google.maps.event.addListener(map, 'dblclick', function(event) {placeMarker(event.latLng, map);} );

		//	Add InfoWindow to show instructions
		addInstructionsInfoWindow(map, location);
 	}

	/*
	 *	Get all the markers for whole map.
	 *	TODO: Later on only get markers for the area in the map.
	 *	Put the markers on the map.
	 *	Add listeners for each marker, to show details for the marker on click.
	 *	TODO: Also have form to add user info on each marker.
	 */
	function populateMarkers(map)
	{
		<?php 
		$allLocations = getMarkersInZone(1, 1, $db); 	//	add end points of map instead of getting all info.
		echo 'var markers = new Array();';
		echo 'var infoWindows = new Array();';
		for( $i = 0; $i < count($allLocations); $i = $i + 2 )
		{
			$index = $i / 2;
			$currLat = $allLocations[$i];
			$currLng = $allLocations[$i+1];
			echo 'var location = new google.maps.LatLng('.$currLat.', '.$currLng.');';
			echo 'markers['.$index.'] = new google.maps.Marker( {position: location, title:"marker'.$index.'", map: map} );';
			$markerDetails = getMarkerDetails($currLat, $currLng, $db);
			echo 'var contentString = "SafetyRating: '.$markerDetails[4].'";';
			echo 'contentString = contentString + "<p> Comments: '.$markerDetails[2].'";';
			echo 'contentString = contentString + "<p> Location: '.$markerDetails[0].', '.$markerDetails[1].'";';
			echo 'infoWindows['.$index.'] = new google.maps.InfoWindow( {content: contentString, maxWidth: 800} );';
			echo 'google.maps.event.addListener( markers['.$index.'], "click", function() { infoWindows['.$index.'].open(map, markers['.$index.']); } );';
		}
		?>
	}

	/*
	 *	When user double clicks a location, add a marker instead of zooming in further.
	 *	Should only work when user is sufficiently zoomed in. 
	 *	Otherwise, just zoom in as normal.
	 *	After adding marker, open the safety warning form.
	 *	Add a onClick() listener for the marker.
	 */
	function placeMarker(location, map) 
	{
		if( map.zoom < 14 )
			return;

		titleString = "Coordinates: " + location;
		var newMarker = new google.maps.Marker( {position: location, title:titleString, map: map} );

    	var contentString = '<div> <b>Current Location: </b> ' + location+
			'<form name="inputForm" method = "post" action = "test.php">' +
			'<input type="hidden" name="isNewEntry" value="true">' +
			'<input type="hidden" name="lat" value=' + location.lat() + '>' +
			'<input type="hidden" name="lng" value=' + location.lng() + '>' +
			'<br />Please rate the safety of this location (from 1-4, 1 being the safest): <br /> '+
			'<input type="radio" name="safetyRating" value="1" checked> 1 ' +
			'<input type="radio" name="safetyRating" value="2" > 2 ' +
			'<input type="radio" name="safetyRating" value="3" > 3 ' +
			'<input type="radio" name="safetyRating" value="4" > 4 ' +
			'<br /><br />Add a note about the safety issues at this location: <br />' +
			'<textarea rows="3" cols = "40" name="safetyComment"></textarea>' +
			'<br /><br /> <input type="submit" value="Submit" />' +
			'</form></div>';

		var infowindow = new google.maps.InfoWindow( {content: contentString, maxWidth: 800} );
		infowindow.open(map, newMarker);

		//		clearListeners(map, 'dblclick'); 		//	doesn't work
		google.maps.event.addListener( newMarker, 'click', function() { infowindow.open(map, newMarker); } );
		// hack to prevent zooming on double click
		google.maps.event.addListener( marker, 'click', function() { infowindow.open(map, marker); } );		
	}

	/*
	 *	Create and add an instructions window to the map at given position.
	 */
	function addInstructionsInfoWindow(map, position)
	{
		var infoWindowInstructions = new google.maps.InfoWindow();
		var contentStringInstructions = "<br />  Welcome to <b> BeSafe 2.0 </b>, the crowdsourced map that shows safety warnings for travellers!" +
		"<p> " +
		" Click on marker on the map to see the safety warnings for that area. " +
		"<p> To add a safety warning at an area for other people, zoom into the area and then double click it. " +
		"<br /> A new marker will appear. Click on it and add your warnings!" + 
		"<p> Travel safely! ";
		infoWindowInstructions.setContent(contentStringInstructions);
		infoWindowInstructions.setPosition(position);
		infoWindowInstructions.open(map);
	}

	</script>
</head>

<body onload="initialize()">
	<div id="map_canvas"></div>
</body>

</html>
